package com.example.springboot_demo.service;

import com.example.springboot_demo.config.WebSocketService;
import com.example.springboot_demo.dao.OrderWmsDao;
import com.example.springboot_demo.model.OrderWms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
    Created with IntelliJ IDEA.
    @Author: 文
    @Date: 2024/12/5
    @Time: 11:21
    To change this template use File | Settings | File Templates.
    @Description: 
*/
@Service
public class OrderWmsService {

    @Autowired
    private OrderWmsDao orderWmsDao;

    // 定义一个常量
    private static final String orderData = "orderData";

    private static final String craneStatus = "craneStatus";
    @Autowired
    private WebSocketService webSocketService;

    private final ExecutorService executorService = Executors.newFixedThreadPool(10);  // 创建线程池

    /**
     * 行车指令信息
     */
    @Scheduled(fixedRate = 15000)  // 每15秒执行一次
    public void scheduledQuery() {
        Future<List<OrderWms>> future = getOrderListAsync();
        try {
            List<OrderWms> orderList = future.get();  // 获取查询结果

            // 获取 WebSocketSession 并推送数据
            webSocketService.sendToClients(orderList,orderData);  // 推送数据到 WebSocket 客户端
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 异步查询数据
    public Future<List<OrderWms>> getOrderListAsync() {
        return executorService.submit(() -> orderWmsDao.getOrderList());
    }

    /**
     * 行车PLC数据 暂时没有通过查询表来代替
     */
    @Scheduled(fixedRate = 15000)  // 每15秒执行一次
    public void scheduledQueryPlc() {
        Future<List<OrderWms>> futures = getOrderPlcListAsync();
        try {
            List<OrderWms> orderPlcList = futures.get();  // 获取查询结果

            // 获取 WebSocketSession 并推送数据
            webSocketService.sendToClients(orderPlcList,craneStatus);  // 推送数据到 WebSocket 客户端
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 异步查询数据
    public Future<List<OrderWms>> getOrderPlcListAsync() {
        return executorService.submit(() -> orderWmsDao.getOrdelPlcList());  // 假设有orderPlcDao查询
    }
}
